package com.springboot_shopping.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.springboot_shopping.entity.*;
import com.springboot_shopping.service.PictureService;
import com.springboot_shopping.service.ProductService;
import com.springboot_shopping.vo.*;
import com.springboot_shopping.vo.PictureUploadRequest;
import com.springboot_shopping.vo.PictureUploadResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private PictureService pictureService;

    //查询所有商品
    @GetMapping("/findAll")
    public List<Product> findAll() {

        return productService.findAll();
    }



    // 分页查询
    @PostMapping("/page")
    public ResultVo getProductPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestBody(required = false) Product product
    ) {
        try {
            IPage<Product> page = productService.getPage(product, pageNum);
            return ResultVo.success("分页查询成功", page);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("分页查询失败: " + e.getMessage());
        }
    }


//图片上传
/*@RequestPart("file")：用于接收表单中的文件部分。
*
* */
@PostMapping("/uploadPicture")
public PictureUploadResponse uploadPicture(
        @RequestPart("file") PictureUploadRequest request
) {
    return pictureService.uploadPicture(request);
}


    // 商品详情展示   http://localhost:8080/product/detailed?id=2
    @GetMapping("/detailed")
    public ResultVo detailed(Integer id) {
        try {
            ProductDetailVo detail = productService.getProductDetail(id);
            if (detail == null) {
                return ResultVo.error("商品不存在");
            }
            return ResultVo.success("商品详情查询成功", detail);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("商品详情查询失败: " + e.getMessage());
        }
    }

    //商品的首页展示，只需显示商品图片和商品名称
    // 商品首页展示
    // 商品首页展示
    @GetMapping("/ProductIndex")
    public ResultVo index() {
        try {
            List<IndexProductVo> products = productService.getProductsForIndex();
            return ResultVo.success("首页商品查询成功", products);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("首页商品查询失败: " + e.getMessage());
        }
    }

}

